from PIL import Image
from django.db import models


class User(models.Model):
    """用户"""
    no = models.AutoField(primary_key=True, verbose_name='编号')
    username = models.CharField(max_length=20, unique=True, verbose_name='用户名')
    password = models.CharField(max_length=32, verbose_name='用户密码')
    tel = models.CharField(max_length=20, default='', verbose_name='手机号')
    regdate = models.DateTimeField(auto_now_add=True, verbose_name='注册日期')
    photo = models.ImageField(null=True, verbose_name='头像')
    intro = models.TextField(default='', verbose_name='自我介绍')

    def save(self, *args, **kwargs):
        super(User, self).save()
        if self.photo:
            image = Image.open(self.photo)
            image.thumbnail((64, 64))
            image.save(self.photo.path)

    class Meta:
        db_table = 'tb_user'
        verbose_name_plural = '用户'


class LoginLog(models.Model):
    """登录日志"""
    no = models.AutoField(primary_key=True, verbose_name='编号')
    ip_addr = models.CharField(max_length=15, verbose_name='IP地址')
    login_date = models.DateTimeField(auto_now_add=True, verbose_name='登录时间日期')
    user = models.ForeignKey(to=User, on_delete=models.PROTECT, db_column='uno', verbose_name='用户')

    class Meta:
        db_table = 'tb_login_log'
        verbose_name_plural = '登录日志'


class Subject(models.Model):
    """学科"""
    no = models.AutoField(primary_key=True, verbose_name='编号')
    name = models.CharField(max_length=31, verbose_name='名称')
    intro = models.CharField(max_length=511, verbose_name='介绍')

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'tb_subject'
        verbose_name_plural = '学科'


class Teacher(models.Model):
    """老师"""
    no = models.AutoField(primary_key=True, verbose_name='编号')
    name = models.CharField(max_length=15, verbose_name='姓名')
    gender = models.BooleanField(default=True, choices=((True, '男'), (False, '女')), verbose_name='性别')
    birth = models.DateField(null=True, verbose_name='出生日期')
    intro = models.CharField(max_length=511, default='', verbose_name='')
    good_count = models.IntegerField(default=0, verbose_name='好评数')
    bad_count = models.IntegerField(default=0, verbose_name='差评数')
    photo = models.CharField(max_length=255, verbose_name='照片')
    subject = models.ForeignKey(to=Subject, on_delete=models.PROTECT, db_column='sno', verbose_name='所属学科')

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'tb_teacher'
        verbose_name_plural = '老师'
